//
//  JSZViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/25.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "JSZViewController.h"
#import "TZImagePickerController.h"

@interface JSZViewController ()<TZImagePickerControllerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>{
    UIImagePickerController *imagepc;
}

@property (weak, nonatomic) IBOutlet UIImageView *image1;
@property (weak, nonatomic) IBOutlet UIImageView *image2;

@property (nonatomic,copy)NSString *state;

@property (nonatomic,copy)NSString *imgUrl1;
@property (nonatomic,copy)NSString *imgUrl2;

@end

@implementation JSZViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self showNav:@"驾驶证认证"];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click1)];
    _image1.userInteractionEnabled = YES;
    [_image1 addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2)];
    _image2.userInteractionEnabled = YES;
    [_image2 addGestureRecognizer:tap2];
    _imgUrl1 = _just;
    _imgUrl2 = _back;
    [_image1 sd_setImageWithURL:[NSURL URLWithString:_just] placeholderImage:[UIImage imageNamed:@""]];
    [_image2 sd_setImageWithURL:[NSURL URLWithString:_back] placeholderImage:[UIImage imageNamed:@""]];
    
}

- (void)click1{
    _state = @"aaa";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从手机相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
    
}
#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    
    if ([_state isEqualToString:@"aaa"]) {
        _image1.image = img;
    }else{
        _image2.image = img;
    }
    
    [self loadImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//上传图片
- (void)loadImage:(UIImage *)image{
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    [parmas setObject:[user objectForKey:@"userid"] forKey:@"userid"];
    if ([_state isEqualToString:@"aaa"]) {//正面
        [parmas setObject:@"justimg" forKey:@"identification"];
    }else{
        [parmas setObject:@"backimg" forKey:@"identification"];
    }
    
    [parmas setObject:@"img.png" forKey:@"img"];
    NSLog(@"parmas:%@",parmas);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/addcarid",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"img" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSString *status = [op objectForKey:@"status"];
        NSLog(@"dic:%@",op);
        if ([status integerValue] == 200) {
            if ([_state isEqualToString:@"aaa"]) {
                _imgUrl1 = [op objectForKey:@"content"];
            }else{
                _imgUrl2 = [op objectForKey:@"content"];
            }
        }
        [LICGToast showWithText:[op objectForKey:@"msg"]];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

- (void)click2{
    _state = @"sss";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从手机相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}


- (IBAction)clickSave:(id)sender {
    if (_imgUrl1.length == 0) {
        [LICGToast showWithText:@"请上传驾驶证正面"];
        return;
    }else if (_imgUrl2.length == 0){
        [LICGToast showWithText:@"请上传驾驶证反面"];
        return;
    }
    
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:token forKey:@"verifyToken"];
    NSString *userid = [NSString stringWithFormat:@"%li",[[user objectForKey:@"userid"] integerValue]] ;
    NSString *url = [NSString stringWithFormat:@"%@/App/Usercenter/index",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        [LICGToast showWithText:@"提交成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
